#!/usr/bin/env python
# -*- coding: utf-8 -*-

'''
# ----------------------------------------------------------------------------
#  Purpose:     用于实现文件上传功能

#  Author:      青衫少年春归也

#  Created:     2019.12.19

# ----------------------------------------------------------------------------
'''

import os
import requests
from minio import Minio


class UploadFile():
    def set_minio_server_info(self, minio_server:str, minio_bucket_name:str, minio_acesskey:str, minio_secretkey:str):
        """
        设置Minio 服务的配置信息
        参数信息:
            :param minio_server:        Minio 服务器地址
            :param minio_bucket_name:   文件要上传到的Minio服务器的bucket
            :param minio_acesskey:      Minio服务器通信所用密钥信息
            :param minio_secretkey:     Minio服务器通信所用密钥信息
        """
        self._minio_server_path = minio_server
        self._minio_bucket_name = minio_bucket_name
        self._minio_acesskey = minio_acesskey
        self._minio_secretkey = minio_secretkey


    def upload_file_to_minio(self, local_file_path:str, file_name:str=None) ->str:
        """
        上传文件到指定的Minio服务器
        参数信息:
            :param file_name          文件名
            :param local_file_path    本地文件路径
        返回值:
            :return 具体的Minio地址
        """
        if not os.path.exists(local_file_path):
            raise FileNotFoundError("本地文件不存在！")
        with open(local_file_path, 'rb') as file_stream:
            size_num = os.stat(local_file_path).st_size
            _name = file_name if file_name else os.path.basename(local_file_path)
            minio = Minio(self._minio_server_path, self._minio_acesskey, self._minio_secretkey, False)
            try:
                minio.put_object(self._minio_bucket_name, _name, file_stream, int(size_num))
            except Exception as e:
                raise ConnectionError(f"上传文件失败！{str(e)}")

            return f"http://{self._minio_server_path}/minio/download/{self._minio_bucket_name}/{_name}?token="


    def download_file_from_minio(self, download_link:str, local_file_path:str):
        """
        从Minio服务器上下载文件并存储到本地
        参数信息：
            :param download_link: 下载地址
            :param local_file_path: 本地存储路径
        """
        headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/34.0.1847.137 Safari/537.36 LBBROWSER'}
        try:
            res = requests.get(download_link, headers=headers, stream=True)
        except Exception as e:
            raise ConnectionError(f'下载失败，连接:{download_link}\n原因为:{str(e)}')

        if not os.path.isdir(os.path.dirname(local_file_path)):
            try:
                os.makedirs(os.path.dirname(local_file_path))
            except Exception as e:
                pass

        with open(local_file_path, "wb") as fs:
            for chunk in res.iter_content(chunk_size=10240):
                if chunk:
                    fs.write(chunk)